#include <chrono>
#include <thread>
#include <vector>
#include <atomic>
#include <iostream>
#include <mutex>
#include <algorithm>
#include <cmath>
#include "shared_parameters/shared_params_interface.hpp"

using namespace std;
using namespace std::chrono;

// 测试配置
constexpr int WARMUP_ITERATIONS = 1000;    // 预热迭代次数
constexpr int MEASURE_ITERATIONS = 100000; // 测量迭代次数
constexpr int THREAD_COUNT = 8;            // 并发线程数
constexpr char NODE_NAME[] = "perf_test";
constexpr char INT_PARAM[] = "int_param";
constexpr char STR_PARAM[] = "str_param";

// 全局统计
atomic<bool> global_start{false};
vector<vector<long long>> latency_data(THREAD_COUNT);
mutex cout_mutex;

// 错误统计
atomic<int> performance_read_errors{0};    // 性能测试读错误
atomic<int> stability_write_errors{0};     // 稳定性测试写错误
atomic<size_t> total_operations{0};

// 初始化测试参数
void setup_test_parameters() {
    if (!SharedParamsInterface::setParam(NODE_NAME, INT_PARAM, 42)) {
        cerr << "初始化整型参数失败" << endl;
    }
    if (!SharedParamsInterface::setParam(NODE_NAME, STR_PARAM, string(100, 'A'))) {
        cerr << "初始化字符串参数失败" << endl;
    }
}

// 性能测试线程
void perf_test_thread(int thread_id, bool test_int, atomic<int>& error_counter) {
    vector<long long> local_latency;
    local_latency.reserve(MEASURE_ITERATIONS);
    const string expected_str(100, 'A');

    while (!global_start.load()) { this_thread::yield(); }

    for (int i = 0; i < MEASURE_ITERATIONS; ++i) {
        auto start = high_resolution_clock::now();
        
        bool error = false;
        if (test_int) {
            int value = SharedParamsInterface::getParam<int>(NODE_NAME, INT_PARAM, -1);
            if (value != 42) {
                error = true;
            }
        } else {
            string value = SharedParamsInterface::getParam<string>(NODE_NAME, STR_PARAM, "");
            if (value != expected_str) {
                error = true;
            }
        }
        
        auto end = high_resolution_clock::now();
        local_latency.push_back(duration_cast<nanoseconds>(end - start).count());
        
        if (error) {
            error_counter.fetch_add(1, memory_order_relaxed);
        }
    }

    latency_data[thread_id] = move(local_latency);
}

// 打印统计结果
void print_statistics(const vector<long long>& data, int error_count) {
    if (data.empty()) return;

    long long sum = 0;
    long long max_val = numeric_limits<long long>::min();
    long long min_val = numeric_limits<long long>::max();
    vector<long long> sorted = data;

    for (auto v : data) {
        sum += v;
        max_val = max(max_val, v);
        min_val = min(min_val, v);
    }

    sort(sorted.begin(), sorted.end());

    cout << "=== 性能统计 ===" << endl;
    cout << "样本数量:    " << data.size() << endl;
    cout << "平均延迟:    " << sum / data.size() << " ns" << endl;
    cout << "最小延迟:    " << min_val << " ns" << endl;
    cout << "最大延迟:    " << max_val << " ns" << endl;
    cout << "P50 延迟:    " << sorted[sorted.size()/2] << " ns" << endl;
    cout << "P95 延迟:    " << sorted[sorted.size()*95/100] << " ns" << endl;
    cout << "P99 延迟:    " << sorted[sorted.size()*99/100] << " ns" << endl;
    
    double throughput = data.size() * 1e9 / sum;
    cout << "吞吐量:      " << throughput << " req/秒" << endl;
    double error_rate = (error_count * 100.0) / data.size();
    cout << "错误率:      " << fixed << setprecision(2) << error_rate << "%" << endl;
}

// 预热缓存
void warmup(bool test_int) {
    for (int i = 0; i < WARMUP_ITERATIONS; ++i) {
        if (test_int) {
            SharedParamsInterface::getParam<int>(NODE_NAME, INT_PARAM, 0);
        } else {
            SharedParamsInterface::getParam<string>(NODE_NAME, STR_PARAM, "");
        }
    }
}

// 内存监控函数
size_t get_current_memory_usage() {
    ifstream statm("/proc/self/statm");
    size_t size, resident, shared, text, lib, data, dt;
    if (statm >> size >> resident >> shared >> text >> lib >> data >> dt) {
        return resident * sysconf(_SC_PAGESIZE) / 1024; // 返回KB为单位
    }
    return 0;
}

// 长时间测试线程函数
void long_running_test(atomic<bool>& stop_flag, vector<long long>& latency_data, 
                      atomic<size_t>& peak_memory, int operation_interval_ms) {
    const auto interval = chrono::milliseconds(operation_interval_ms);
    const int max_value = 100;
    const string param_name = INT_PARAM;
    
    while (!stop_flag.load()) {
        auto op_start = high_resolution_clock::now();
        
        // 带校验的混合操作
        bool is_write = (rand() % 4 == 0);
        bool operation_success = true;
        
        if (is_write) {
            int new_value = rand() % max_value;
            if (!SharedParamsInterface::setParam(NODE_NAME, param_name, new_value)) {
                stability_write_errors.fetch_add(1);
                operation_success = false;
            }
        } else {
            int value = SharedParamsInterface::getParam<int>(NODE_NAME, param_name, -1);
            if (value < 0 || value >= max_value) {
                operation_success = false;
            }
        }
        
        // 记录操作延迟（仅记录成功操作）
        if (operation_success) {
            auto op_end = high_resolution_clock::now();
            latency_data.push_back(duration_cast<nanoseconds>(op_end - op_start).count());
        }

        // 内存监控
        size_t current_mem = get_current_memory_usage();
        size_t prev_mem = peak_memory.load();
        while (current_mem > prev_mem && 
              !peak_memory.compare_exchange_weak(prev_mem, current_mem)) {}
        
        this_thread::sleep_until(op_start + interval);
    }
}

// 监控线程函数
void memory_monitor(atomic<bool>& stop_flag, atomic<size_t>& peak_memory) {
    ofstream mem_log("memory_usage.log");
    auto start = high_resolution_clock::now();
    
    while (!stop_flag.load()) {
        // 记录内存和耗时
        auto now = high_resolution_clock::now();
        auto elapsed = duration_cast<seconds>(now - start);
        size_t current_mem = get_current_memory_usage();
        
        // 更新峰值内存
        size_t prev_mem = peak_memory.load();
        while (current_mem > prev_mem && 
             !peak_memory.compare_exchange_weak(prev_mem, current_mem)) {}
        
        // 修正变量名
        mem_log << elapsed.count() << "s\t" 
               << current_mem << " KB\t"
               << peak_memory.load() << " KB\n"; 
        
        this_thread::sleep_for(1s);
    }
}

int main() {
    // 初始化共享内存
    if (!SharedParamsInterface::initialize()) {
        cerr << "共享内存初始化失败！" << endl;
        return EXIT_FAILURE;
    }
    setup_test_parameters();

    // 测试整型参数
    {
        cout << "\n*​**​ 测试整型参数性能 ​**​*" << endl;
        vector<thread> threads;
        atomic<int> error_counter{0};
        global_start.store(false);
        
        // 创建测试线程
        for (int i = 0; i < THREAD_COUNT; ++i) {
            threads.emplace_back(perf_test_thread, i, true, ref(error_counter));
        }

        // 预热缓存
        warmup(true);
        
        // 统一启动测试
        auto test_start = high_resolution_clock::now();
        global_start.store(true);
        
        // 等待完成
        for (auto& t : threads) {
            t.join();
        }
        auto test_end = high_resolution_clock::now();

        // 合并结果
        vector<long long> all_latency;
        for (auto& vec : latency_data) {
            all_latency.insert(all_latency.end(), vec.begin(), vec.end());
        }

        // 显示结果
        print_statistics(all_latency, error_counter.load());
        cout << "总测试时间: " 
             << duration_cast<milliseconds>(test_end - test_start).count()
             << " ms" << endl;
    }

    // 测试字符串参数
    {
        cout << "\n*​**​ 测试字符串参数性能 ​**​*" << endl;
        vector<thread> threads;
        global_start.store(false);
         atomic<int> error_counter{0};
        latency_data = vector<vector<long long>>(THREAD_COUNT);

        // 创建测试线程
        for (int i = 0; i < THREAD_COUNT; ++i) {
            threads.emplace_back(perf_test_thread, i, false, ref(error_counter));
        }

        // 预热缓存
        warmup(false);
        
        // 统一启动测试
        auto test_start = high_resolution_clock::now();
        global_start.store(true);
        
        // 等待完成
        for (auto& t : threads) {
            t.join();
        }
        auto test_end = high_resolution_clock::now();

        // 合并结果
        vector<long long> all_latency;
        for (auto& vec : latency_data) {
            all_latency.insert(all_latency.end(), vec.begin(), vec.end());
        }

        // 显示结果
        print_statistics(all_latency, error_counter.load());
        cout << "总测试时间: " 
             << duration_cast<milliseconds>(test_end - test_start).count()
             << " ms" << endl;
    }


    // 长时间稳定性测试
    {
        cout << "\n*​**​ 长时间稳定性测试 (持续10分钟) ​**​*" << endl;
        constexpr int TEST_DURATION_MIN = 5;     // 测试持续时间（分钟）
        constexpr int OPERATION_INTERVAL_MS = 50; // 操作间隔50ms（20次/秒）
        
        atomic<bool> stop_flag{false};
        vector<long long> latency_data;
        atomic<size_t> peak_memory{0};
        size_t initial_memory = get_current_memory_usage();

        // 启动监控线程
        thread monitor([&]() { 
            memory_monitor(stop_flag, peak_memory); 
        });
        
        // 启动测试线程
        thread test_thread([&]() {
            long_running_test(stop_flag, latency_data, peak_memory, OPERATION_INTERVAL_MS);
        });
        
        // 等待测试持续时间
        this_thread::sleep_for(chrono::minutes(TEST_DURATION_MIN));
        stop_flag = true;
        
        // 等待线程结束
        test_thread.join();
        monitor.join();

        // 输出统计结果
        cout << "\n=== 稳定性测试结果 ===" << endl;
        cout << "总操作次数: " << latency_data.size() << endl;
        cout << "平均操作频率: " 
             << latency_data.size() / (TEST_DURATION_MIN * 60.0) << " 次/秒" << endl;
        print_statistics(latency_data, stability_write_errors.load());
        
        // 内存分析
        cout << "\n=== 内存使用分析 ===" << endl;
        cout << "初始内存: " << initial_memory << " KB" << endl;
        cout << "峰值内存: " << peak_memory.load() << " KB" << endl;
        cout << "最终内存: " << get_current_memory_usage() << " KB" << endl;
        cout << "内存变化: " << (get_current_memory_usage() - initial_memory) << " KB" << endl;
        
        // 生成性能报告
        ofstream report("long_test_report.csv");
        report << "操作耗时(ms),内存使用(KB)\n";
        for (size_t i = 0; i < latency_data.size(); ++i) {
            report << latency_data[i] / 1e6 << ","
                   << get_current_memory_usage() << "\n";
            if (i % 100 == 0) this_thread::sleep_for(1ms); // 防止写入过快
        }
    }

    return EXIT_SUCCESS;
}